package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");

        User userLogin = objectMapper.readValue(req.getInputStream(), User.class);
        String username = userLogin.getUserName();
        String password = userLogin.getPassword();

        if (username == null || "".equals(username) || password == null || "".equals(password)){
            // 登录失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("fail");
            return;
        }
        // 和数据库的进行比较
        UserDao userDao = new UserDao();
        User user = userDao.selectUser(username);// 拿到 user用户
        if (user == null || !user.getPassword().equals(password)){
            // 登录失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("fail");
            return;
        }

        // 创建会话
        HttpSession session = req.getSession();
        session.setAttribute("user", user);// 存储用户信息
        resp.getWriter().write("success");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/json; charset=utf8");
        // 让前端检测当前的登录状态
        HttpSession session = req.getSession(false);
        if (session == null){
            // 检测会话是否存在 ,不存在则未登录
            User user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        User user = (User) session.getAttribute("user");// 会话里有没有 user对象
        if (user == null){
            user = new User();
            resp.getWriter().write(objectMapper.writeValueAsString(user));
            return;
        }
        // 不应该把密码返回
        user.setPassword("");

        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
